<template>
  <div class="login-container">
    <!-- 左侧品牌区域 -->
    <div class="left-panel">
      <!-- 图片 -->
      <img 
        src="../static/background.png" 
        alt="background" 
        class="background-image"
      />
      
      <!-- 左上角品牌信息 -->
      <div class="brand-header">
        <div class="logo-icon">
          <svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <path d="M22 20v-5h-3a5 5 0 0 1-5-5v-3a5 5 0 0 1 5-5h3v13z"></path>
            <path d="M18 10a3 3 0 0 1 3 3v4a3 3 0 0 1-3 3h-4l-8-10v-3h6a3 3 0 0 1 3 3z"></path>
            <path d="m12 12-2-1-1-1"></path>
          </svg>
        </div>
        <div class="brand-info">
          <h1 class="brand-title">流浪动物救助系统</h1>
          <p class="brand-subtitle">呵护每一个生命，传递温暖与希望</p>
        </div>
      </div>

      <!-- 底部公司信息 -->
      <div class="company-info">
        <p class="company-name">流浪动物救助中心</p>
        <p class="company-slogan">用爱心呵护每一个生命</p>
      </div>
    </div>

    <!-- 右侧登录区域 -->
    <div class="right-panel">
      <div class="login-content">
        <div class="login-header">
          <h2 class="login-title">登录</h2>
          <p class="login-subtitle">欢迎回来，请登录您的账户</p>
        </div>

        <el-form :model="form" class="login-form">
          <!-- 用户名 -->
          <el-form-item>
            <el-input 
              v-model="form.username" 
              placeholder="请输入用户名/手机号"
              size="large"
              class="input-item"
            >
              <template #prefix>
                <el-icon class="input-icon"><User /></el-icon>
              </template>
            </el-input>
          </el-form-item>

          <!-- 密码 -->
          <el-form-item>
            <el-input 
              v-model="form.password" 
              type="password" 
              placeholder="请输入密码"
              size="large"
              class="input-item"
              show-password
            >
              <template #prefix>
                <el-icon class="input-icon"><Lock /></el-icon>
              </template>
            </el-input>
          </el-form-item>

          <!-- 验证码 -->
          <el-form-item style="margin-top: 8px;">
            <div class="captcha-row">
              <el-input 
                v-model.number="form.captcha" 
                placeholder="验证码"
                size="large"
                class="captcha-input"
              >
                <template #prefix>
                  <el-icon class="input-icon"><Grid /></el-icon>
                </template>
              </el-input>
              <div class="captcha-box" @click="generateCaptcha">
                <canvas
                  ref="captchaCanvas"
                  width="100"
                  height="40"
                  class="captcha-canvas"
                  style="width: 100px; height: 40px;"
                ></canvas>
              </div>
            </div>
          </el-form-item>

          <!-- 30天自动登录和隐私服务 -->
          <div class="checkbox-row">
            <el-checkbox v-model="rememberLogin" class="remember-checkbox">
              30天自动登录
            </el-checkbox>
            <el-checkbox v-model="privacyAgree" class="privacy-checkbox">
              我已阅读并同意<span class="privacy-link" @click="showPrivacyDialog = true">《隐私服务协议》</span>
            </el-checkbox>
          </div>

          <!-- 登录按钮 -->
          <el-button 
            type="primary" 
            @click="login" 
            size="large"
            class="login-button"
          >
            立即登录
          </el-button>

          <!-- 注册链接和忘记密码 -->
          <div class="action-links">
           
            <span class="register-link">
              还没有账号？
              <span @click="$router.push('/register')">立即注册</span>
            </span> 
            <span class="forgot-link" @click="showForgotPasswordDialog = true">忘记密码？</span>
          </div>

          <!-- 第三方登录 -->
          <div class="third-party-login">
            <div class="divider">
              <span class="divider-text">其他登录方式</span>
            </div>
            <div class="third-party-icons">
              <div class="third-party-item wechat" @click="handleThirdPartyLogin('wechat')" title="微信登录">
                <Icon icon="mdi:wechat" width="26" height="26" />
              </div>
              <div class="third-party-item qq" @click="handleThirdPartyLogin('qq')" title="QQ登录">
                <Icon icon="mdi:qqchat" width="26" height="26" />
              </div>
            </div>
          </div>
        </el-form>
      </div>
    </div>

    <!-- 忘记密码弹窗 -->
    <el-dialog
      v-model="showForgotPasswordDialog"
      title="重置密码"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form :model="forgotPasswordForm" label-width="100px">
        <el-form-item label="手机号码">
          <el-input v-model="forgotPasswordForm.phone" placeholder="请输入手机号码" />
        </el-form-item>
        <el-form-item label="新密码">
          <el-input v-model="forgotPasswordForm.newPassword" type="password" placeholder="请输入新密码" show-password />
        </el-form-item>
        <el-form-item label="确认密码">
          <el-input v-model="forgotPasswordForm.confirmPassword" type="password" placeholder="请再次输入新密码" show-password />
        </el-form-item>
        <el-form-item label="验证码">
          <div class="captcha-row">
            <el-input v-model="forgotPasswordForm.smsCode" placeholder="请输入验证码" />
            <el-button :disabled="smsCountdown > 0" @click="sendSmsCode">
              {{ smsCountdown > 0 ? `${smsCountdown}秒后重试` : '发送验证码' }}
            </el-button>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showForgotPasswordDialog = false">取消</el-button>
        <el-button type="primary" @click="resetPassword">确认重置</el-button>
      </template>
    </el-dialog>

    <!-- 隐私协议弹窗 -->
    <el-dialog
      v-model="showPrivacyDialog"
      title="隐私服务协议"
      width="800px"
    >
      <div class="privacy-content">
        <h3>一、信息收集</h3>
        <p>我们可能收集以下信息：</p>
        <ul>
          <li>个人信息：姓名、手机号码、邮箱地址等</li>
          <li>设备信息：IP地址、浏览器类型等</li>
          <li>使用信息：登录记录、操作日志等</li>
        </ul>

        <h3>二、信息使用</h3>
        <p>我们使用收集的信息用于：</p>
        <ul>
          <li>提供和改进我们的服务</li>
          <li>与您沟通，包括服务通知和客户支持</li>
          <li>检测和防范安全威胁、欺诈或非法活动</li>
        </ul>

        <h3>三、信息保护</h3>
        <p>我们采用行业标准的安全措施保护您的信息，包括：</p>
        <ul>
          <li>数据加密传输和存储</li>
          <li>访问控制和权限管理</li>
          <li>定期安全审计和更新</li>
        </ul>

        <h3>四、信息分享</h3>
        <p>我们不会向第三方出售、交易或转让您的个人信息，除非：</p>
        <ul>
          <li>获得您的明确同意</li>
          <li>法律法规要求</li>
          <li>保护我们的权利和财产</li>
        </ul>

        <h3>五、Cookie使用</h3>
        <p>我们使用Cookie和类似技术来：</p>
        <ul>
          <li>记住您的登录状态和偏好设置</li>
          <li>分析网站流量和用户行为</li>
          <li>提供个性化内容和广告</li>
        </ul>

        <h3>六、联系我们</h3>
        <p>如您对本隐私政策有任何疑问，请联系我们：</p>
        <p>邮箱：privacy@animal-rescue.org<br/>电话：400-123-4567</p>
      </div>
      <template #footer>
        <el-button type="primary" @click="acceptPrivacy">我已阅读并同意</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import axios from "axios";
import { User, Lock, Grid } from "@element-plus/icons-vue";
import { Icon } from "@iconify/vue";

export default {
  components: {
    User,
    Lock,
    Grid,
    Icon,
  },
  data() {
    return {
      form: {
        username: "",
        password: "",
        captcha: "",
      },
      captchaAnswer: 0, // JS 保存答案
      rememberLogin: true, // 30天自动登录
      privacyAgree: true, // 隐私服务协议
      showForgotPasswordDialog: false, // 忘记密码弹窗
      showPrivacyDialog: false, // 隐私协议弹窗
      forgotPasswordForm: {
        phone: "",
        newPassword: "",
        confirmPassword: "",
        smsCode: "",
      },
      smsCountdown: 0, // 短信验证码倒计时
    };
  },
  mounted() {
    this.generateCaptcha();
  },
  methods: {
    // 第三方登录
    handleThirdPartyLogin(type) {
      this.$message.info(`${type === 'wechat' ? '微信' : 'QQ'}登录功能即将上线`);
    },
    
    // 发送短信验证码
    sendSmsCode() {
      if (!this.forgotPasswordForm.phone) {
        this.$message.warning("请输入手机号码");
        return;
      }
      if (!/^1[3-9]\d{9}$/.test(this.forgotPasswordForm.phone)) {
        this.$message.error("请输入正确的手机号码");
        return;
      }
      
      // 模拟发送短信验证码
      this.$message.success("验证码已发送至您的手机");
      this.smsCountdown = 60;
      const timer = setInterval(() => {
        this.smsCountdown--;
        if (this.smsCountdown === 0) {
          clearInterval(timer);
        }
      }, 1000);
    },
    
    // 重置密码
    resetPassword() {
      if (!this.forgotPasswordForm.phone) {
        this.$message.warning("请输入手机号码");
        return;
      }
      if (!this.forgotPasswordForm.newPassword) {
        this.$message.warning("请输入新密码");
        return;
      }
      if (this.forgotPasswordForm.newPassword !== this.forgotPasswordForm.confirmPassword) {
        this.$message.error("两次输入的密码不一致");
        return;
      }
      if (!this.forgotPasswordForm.smsCode) {
        this.$message.warning("请输入验证码");
        return;
      }
      
      // 模拟重置密码
      this.$message.success("密码重置成功，请使用新密码登录");
      this.showForgotPasswordDialog = false;
      this.forgotPasswordForm = {
        phone: "",
        newPassword: "",
        confirmPassword: "",
        smsCode: "",
      };
    },
    
    // 接受隐私协议
    acceptPrivacy() {
      this.privacyAgree = true;
      this.showPrivacyDialog = false;
    },
    
    // 生成验证码
    generateCaptcha() {
      const canvas = this.$refs.captchaCanvas;
      const ctx = canvas.getContext("2d");

      // 随机数字和运算符
      const num1 = Math.floor(Math.random() * 10);
      const num2 = Math.floor(Math.random() * 10);
      const operators = ["+", "-", "*"];
      const op = operators[Math.floor(Math.random() * operators.length)];

      // 计算答案
      switch (op) {
        case "+": this.captchaAnswer = num1 + num2; break;
        case "-": this.captchaAnswer = num1 - num2; break;
        case "*": this.captchaAnswer = num1 * num2; break;
      }

      // 清空画布
      ctx.fillStyle = "#ffffff";
      ctx.fillRect(0, 0, canvas.width, canvas.height);

      // 绘制算术题
      ctx.font = "bold 18px Arial";
      ctx.fillStyle = "#303133";
      ctx.fillText(`${num1} ${op} ${num2} = ?`, 12, 25);

      // 随机干扰点
      for (let i = 0; i < 50; i++) {
        ctx.fillStyle = `rgba(${Math.random()*255},${Math.random()*255},${Math.random()*255},0.5)`;
        ctx.fillRect(Math.random()*canvas.width, Math.random()*canvas.height, 2, 2);
      }

      // 随机干扰线
      for (let i = 0; i < 3; i++) {
        ctx.strokeStyle = `rgba(${Math.random()*255},${Math.random()*255},${Math.random()*255},0.3)`;
        ctx.lineWidth = 1;
        ctx.beginPath();
        ctx.moveTo(Math.random()*canvas.width, Math.random()*canvas.height);
        ctx.lineTo(Math.random()*canvas.width, Math.random()*canvas.height);
        ctx.stroke();
      }

      // 刷新验证码时清空输入框
      this.form.captcha = "";
    },

    async login() {
      // 验证验证码
      if (Number(this.form.captcha) !== this.captchaAnswer) {
        this.$message.error("验证码错误");
        this.generateCaptcha();
        return;
      }

      try {
        const res = await axios.post("http://localhost:8080/api/auth/login", {
          username: this.form.username,
          password: this.form.password
        });

        if (res.data.code === 200) {
          // 检查账号状态
          if (res.data.status !== undefined && res.data.status !== 1) {
            this.$message.error("账号被封禁，请联系管理员处理");
            this.generateCaptcha();
            return;
          }

          this.$message.success("登录成功");

          // 保存登录状态到 localStorage
          localStorage.setItem("isLoggedIn", "true");
          localStorage.setItem("roleId", res.data.roleId);
          localStorage.setItem("userId", res.data.userId);
          localStorage.setItem("nickname", res.data.nickname);

          // 根据角色跳转
          const role = res.data.roleId;
          if (role === 1) this.$router.push("/user/dashboard");
          else if (role === 2) this.$router.push("/volunteer/dashboard");
          else if (role === 3) this.$router.push("/admin/home");
        } else {
          this.$message.error(res.data.msg);
          this.generateCaptcha(); // 登录失败刷新验证码
        }
      } catch (error) {
        // 检查是否是账号被封禁的情况
        if (error.response?.data?.code === 403 || error.response?.data?.msg?.includes('封禁') || error.response?.data?.msg?.includes('禁用')) {
          this.$message.error("账号被封禁，请联系管理员处理");
        } else {
          this.$message.error(error.response?.data?.msg || "登录失败，请检查服务器或网络");
        }
        this.generateCaptcha();
      }
    },
  },
};
</script>

<style scoped>
.login-container {
  display: flex;
  height: 100vh;
  overflow: hidden;
  background: #f8f9fa;
}

/* 左侧品牌区域 - 约占60% */
.left-panel {
  width: 60%;
  position: relative;
  overflow: hidden;
  background: #fafbfc;
  display: flex;
  flex-direction: column;
}

.background-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  filter: brightness(1.1) saturate(1.1) contrast(0.95);
  mask-image: linear-gradient(to right, rgba(0,0,0,1) 80%, rgba(0,0,0,0.2) 92%, rgba(0,0,0,0) 100%);
  -webkit-mask-image: linear-gradient(to right, rgba(0,0,0,1) 80%, rgba(0,0,0,0.2) 92%, rgba(0,0,0,0) 100%);
}

.brand-header {
  position: absolute;
  top: 50px;
  left: 50px;
  z-index: 3;
  display: flex;
  align-items: center;
  gap: 16px;
}

.logo-icon {
  width: 56px;
  height: 56px;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
  flex-shrink: 0;
}

.logo-icon svg {
  color: #52c41a;
}

.brand-info {
  text-align: left;
}

.brand-title {
  font-size: 36px;
  font-weight: 700;
  margin: 0 0 8px 0;
  color: #1a1a1a;
  line-height: 1.2;
}

.brand-subtitle {
  font-size: 15px;
  margin: 0;
  color: #4a5568;
  font-weight: 400;
  line-height: 1.4;
}

.company-info {
  position: absolute;
  bottom: 60px;
  left: 50px;
  z-index: 3;
  text-align: left;
}

.company-name {
  font-size: 22px;
  font-weight: 600;
  margin: 0 0 6px 0;
  color: #1a1a1a;
  text-shadow: 0 1px 4px rgba(255, 255, 255, 0.3);
}

.company-slogan {
  font-size: 13px;
  margin: 0;
  color: #606266;
  font-weight: 400;
}

/* 右侧登录区域 */
.right-panel {
  width: 40%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #ffffff;
  padding: 0 80px;
}

.login-content {
  width: 100%;
  max-width: 420px;
}

.login-header {
  margin-bottom: 45px;
  text-align: center;
}

.login-title {
  font-size: 32px;
  font-weight: 600;
  color: #1a1a1a;
  margin: 0 0 8px 0;
}

.login-subtitle {
  font-size: 15px;
  color: #8c8c8c;
  margin: 0;
}

/* 表单样式 */
.login-form {
  width: 100%;
}

.login-form :deep(.el-form-item) {
  margin-bottom: 24px;
}

.input-item :deep(.el-input__wrapper) {
  border-radius: 6px;
  border: 1px solid #dcdee0;
  box-shadow: none;
  transition: all 0.3s ease;
  background: #fafbfc;
}

.input-item :deep(.el-input__wrapper:hover) {
  border-color: #409eff;
  background: white;
}

.input-item :deep(.el-input__wrapper.is-focus) {
  border-color: #409eff;
  background: white;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.1);
}

.input-item :deep(.el-input__prefix) {
  padding-left: 14px;
}

.input-icon {
  color: #8c8c8c;
  font-size: 18px;
}

/* 注册链接和忘记密码 */
.action-links {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
  font-size: 14px;
}

.forgot-link {
  color: #409eff;
  cursor: pointer;
  font-size: 14px;
  transition: color 0.3s ease;
}

.forgot-link:hover {
  color: #67c23a;
}

.register-link {
  color: #8c8c8c;
}

.register-link span {
  color: #409eff;
  font-weight: 500;
  cursor: pointer;
  transition: color 0.3s ease;
  margin-left: 4px;
}

.register-link span:hover {
  color: #67c23a;
}

.captcha-row {
  display: flex;
  gap: 12px;
  align-items: flex-start;
  width: 100%;
}

.captcha-input {
  flex: 1;
  min-width: 0;
}

.captcha-input :deep(.el-input__wrapper) {
  border-radius: 6px;
  border: 1px solid #dcdee0;
  background: #fafbfc;
}

.captcha-input :deep(.el-input__wrapper:hover) {
  border-color: #409eff;
  background: white;
}

.captcha-input :deep(.el-input__wrapper.is-focus) {
  border-color: #409eff;
  background: white;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.1);
}

.captcha-box {
  width: 100px;
  height: 40px;
  border: 1px solid #dcdee0;
  border-radius: 6px;
  cursor: pointer;
  overflow: hidden;
  transition: all 0.3s ease;
  background: #fafbfc;
  flex-shrink: 0;
}

.captcha-box:hover {
  border-color: #409eff;
  background: white;
}

.captcha-canvas {
  width: 100%;
  height: 100%;
  display: block;
}

/* 复选框样式 */
.checkbox-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.remember-checkbox,
.privacy-checkbox {
  margin: 0;
  font-size: 14px;
  color: #606266;
}

.privacy-link {
  color: #409eff;
  cursor: pointer;
  transition: color 0.3s ease;
}

.privacy-link:hover {
  color: #67c23a;
}

/* 登录按钮 */
.login-button {
  width: 100%;
  height: 50px;
  border-radius: 6px;
  font-size: 16px;
  font-weight: 500;
  background: #409eff;
  border: none;
  transition: all 0.3s ease;
  margin-bottom: 24px;
  margin-top: 8px;
}

.login-button:hover {
  background: #66b1ff;
}

.login-button:active {
  transform: translateY(1px);
}

/* 第三方登录 */
.third-party-login {
  margin-top: 32px;
}

.divider {
  display: flex;
  align-items: center;
  text-align: center;
  margin-bottom: 20px;
}

.divider::before,
.divider::after {
  content: '';
  flex: 1;
  border-bottom: 1px solid #dcdee0;
}

.divider-text {
  padding: 0 16px;
  font-size: 13px;
  color: #8c8c8c;
}

.third-party-icons {
  display: flex;
  justify-content: center;
  gap: 20px;
}

.third-party-item {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  background: #f5f7fa;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s ease;
  border: 1px solid #e4e7ed;
}

.third-party-item:hover {
  background: #ebedf0;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.third-party-item svg {
  color: #606266;
}

.third-party-item.wechat svg {
  color: #07C160;
}

.third-party-item.qq svg {
  color: #12B7F5;
}

/* 隐私协议内容 */
.privacy-content {
  max-height: 500px;
  overflow-y: auto;
  padding: 20px 10px;
  line-height: 1.8;
}

.privacy-content h3 {
  color: #303133;
  font-size: 16px;
  font-weight: 600;
  margin: 20px 0 12px 0;
}

.privacy-content p {
  color: #606266;
  font-size: 14px;
  margin: 12px 0;
}

.privacy-content ul {
  margin: 12px 0;
  padding-left: 24px;
}

.privacy-content li {
  color: #606266;
  font-size: 14px;
  margin: 8px 0;
}


/* 响应式设计 */
@media (max-width: 992px) {
  .login-container {
    flex-direction: column;
  }

  .left-panel {
    width: 100%;
    height: 400px;
  }

  .right-panel {
    width: 100%;
    padding: 60px 50px;
  }

  .brand-header {
    left: 30px;
    top: 30px;
  }

  .brand-title {
    font-size: 28px;
  }

  .brand-subtitle {
    font-size: 14px;
  }

  .logo-icon {
    width: 48px;
    height: 48px;
  }

  .company-info {
    left: 30px;
    bottom: 30px;
  }

  .company-name {
    font-size: 20px;
  }

  .company-slogan {
    font-size: 12px;
  }
}

@media (max-width: 576px) {
  .left-panel {
    height: 300px;
  }

  .brand-header {
    left: 20px;
    top: 20px;
    gap: 12px;
  }

  .brand-title {
    font-size: 24px;
  }

  .brand-subtitle {
    font-size: 13px;
  }

  .logo-icon {
    width: 44px;
    height: 44px;
  }

  .company-info {
    left: 20px;
    bottom: 20px;
  }

  .company-name {
    font-size: 18px;
  }

  .company-slogan {
    font-size: 11px;
  }

  .login-title {
    font-size: 26px;
  }

  .login-subtitle {
    font-size: 13px;
  }

  .right-panel {
    padding: 40px 30px;
  }

  .login-header {
    margin-bottom: 35px;
  }
}
</style>

